package com.wy.pdf_test;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.file.Files;

@RestController
public class PdfController2 {

    @GetMapping("/gen3-pdf")
    public String generatePdf() throws Exception {
        // 1. 加载 classpath 中的 HTML 文件
        ClassPathResource htmlResource = new ClassPathResource("templates/examReport.html");
        File tempHtmlFile = File.createTempFile("temp", ".html");
        try (InputStream in = htmlResource.getInputStream();
             OutputStream out = new FileOutputStream(tempHtmlFile)) {
            in.transferTo(out);
        }

        // 2. 定义输出 PDF 路径
        File outputPdf = new File("output.pdf");

        // 3. 调用 wkhtmltopdf 命令
        ProcessBuilder pb = new ProcessBuilder(
                "D:\\devTool\\wkhtmltopdf\\bin\\wkhtmltopdf",
                "--page-size", "A4",
                "--enable-local-file-access",
                "--zoom", "1.0",
                "--disable-smart-shrinking",
                "--encoding", "UTF-8",
                tempHtmlFile.getAbsolutePath(),
                outputPdf.getAbsolutePath()
        );
        pb.redirectErrorStream(true);
        Process process = pb.start();

        // 可选：读取输出日志
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("❌ wkhtmltopdf 失败，退出码：" + exitCode);
        }

        return "✅ PDF 生成成功，位置：" + outputPdf.getAbsolutePath();
    }
}
